import { defineComponent, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  ElDialog,
  ElButton,
  ElIcon,
  ElMessage,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElSwitch
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import type { EventSetPropsType } from './typings'

export default defineComponent({
  name: 'ConnectSet',
  props: ['visible', 'record'],
  emits: ['cancel'],
  setup(props: EventSetPropsType, { emit }) {
    const store = useStore()
    const router = useRouter()
    const state = reactive({
      list: [],
      eventLevelOpt: [
        { name: '一般事件', value: '1' },
        { name: '重要事件', value: '2' }
      ]
    })
    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 提交表单
    const handleSubmitForm = async () => {
      const { id } = router.currentRoute.value.query
      const params = {
        id,
        list: state.list
      }
      const res = await store.dispatch('equipment/UpdateEventPut', params)
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        handleCloseModal()
      }
    }

    onMounted(() => {
      state.list = props.record
    })

    return () => {
      const { visible } = props
      return (
        <ElDialog
          title="事件参数"
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={{
            footer: () => (
              <>
                <ElButton type="primary" onClick={handleSubmitForm}>
                  <ElIcon>
                    <EditPen />
                  </ElIcon>
                  &nbsp; 确定
                </ElButton>
                <ElButton onClick={handleCloseModal}>取消</ElButton>
              </>
            )
          }}
        >
          <ElTable data={state.list} border height={500}>
            <ElTableColumn prop="eventCode" label="事件代码" />
            <ElTableColumn prop="eventName" label="事件名称" />
            <ElTableColumn
              prop="isOpen"
              label="是否记录"
              v-slots={{
                default: (scope: any) => (
                  <ElSwitch v-model={scope.row.isOpen} active-value={1} inactive-value={0} />
                )
              }}
            />
            <ElTableColumn
              prop="eventLevel"
              label="事件等级"
              v-slots={{
                default: (scope: any) => (
                  <ElSelect v-model={scope.row.eventLevel}>
                    {state.eventLevelOpt?.map((item: any) => (
                      <ElOption key={item?.value} label={item?.name} value={item?.value} />
                    ))}
                  </ElSelect>
                )
              }}
            />
          </ElTable>
        </ElDialog>
      )
    }
  }
})
